import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';

class ExchangeController extends GetxController {
  ExchangeController(this.tag, this.modelNum, this.id);

  /// 成员变量
  String? id;
  final String tag;
  final String modelNum;

  final productList = [].obs;

  /// 事件
  Future<void> changeVape(int index) async {
    await Request().post('/userVape/changeVape', {
      'type': tag,
      'targetId': productList[index]['id'],
    }).then((result) {
      toast('Success');
      EventService.to.sendMessage(EventService.EventRefresh);
      Navigator.pop(Get.context!);
    });
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    ever(EventService.to.message, (message) async {
      if (message.startsWith(EventService.EventRefresh)) {
        await Request().get('/userVape/getList', {
          'type': tag,
          'modelNum': modelNum,
        }).then((result) {
          result['result'].forEach((element) {
            element['isSelected'] = element['id'] == id;
          });
          productList.value = result['result'];
        });
      }
    });
  }

  @override
  void onReady() async {
    super.onReady();
    await Request().get('/userVape/getList', {
      'type': tag,
      'modelNum': modelNum,
    }).then((result) {
      result['result'].forEach((element) {
        element['isSelected'] = element['id'] == id;
      });
      productList.value = result['result'];
    });
  }
}
